﻿using MiniFox.Components.Configurations;
using MiniFox.Exceptions;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

using System.Globalization;
using System.Reflection;
using MiniFox.Configurations;

namespace MiniFox.Components
{
    /// <summary>
    /// 
    /// </summary>
    internal class DefaultComponentBuilder : ComponentBuilder
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="componentConfig"></param>
        public DefaultComponentBuilder(IComponentConfig componentConfig)
            : base(componentConfig)
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="componentName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public override object CreateComponent(string componentName, params object[] args)
        {
            if (string.IsNullOrWhiteSpace(componentName))
            {
                throw new InvalidOperationException(string.Format(Resources.CommonMessages.EXPTN_ComponentConfig, this.ContractType.FullName, componentName));
            }
            if (this.Providers.Count <= 0)
            {
                return null;
            }
            ComponentProvider setting = this.Providers[componentName];
            if (setting == null)
                return null;
            Type type = setting.Type;
            SectionAttribute sectionAttribute = type.GetCustomAttribute<SectionAttribute>();
            if (sectionAttribute == null)
            {
                return Activator.CreateInstance(type, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, args, CultureInfo.CurrentCulture);
            }
            else
            {
                return ConfigurationFactory.GetConfig(type);
            }
            
        }
    }

}
